package com.sinai.mshab.client.formatting;

import java.util.Date;

import org.zenika.widget.client.datePicker.DatePicker;

import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * This class is responsible for cloning GWT widgets.
 * 
 * @author serge
 * 
 */
public class CloneManager {

	/**
	 * Clones the given widget.
	 * 
	 * @param given
	 *            the widget to clone
	 * @return a clone of the given widget.
	 */
	public static Widget clone(Widget given) {

		Widget widget = null;

		// simple date picker
		if (given instanceof DatePicker) {
			widget = new DatePicker();
		}
		// a clone for texbox, simple.
		else if (given instanceof TextBox) {
			widget = new TextBox();
		}
		// a clone for checkbox, we need to carry over the text.
		else if (given instanceof CheckBox) {
			String text = ((CheckBox) given).getText();
			widget = new CheckBox(text);
		}
		// clone for list box, we need to carry over the items.
		else if (given instanceof ListBox) {
			ListBox list = (ListBox) given;
			widget = new ListBox();
			for (int i = 0; i < list.getItemCount(); i++) {
				((ListBox) widget).addItem(list.getItemText(i));
			}
		}
		// clone for label, we need to carry over the label text.
		else if (given instanceof Label) {
			String text = ((Label) given).getText();
			widget = new Label(text);
		}
		// clone for file upload, we need to carry over the label text.
		else if (given instanceof FileUpload) {
			widget = new FileUpload();
			((FileUpload) (widget)).setName("upload" + new Date().getTime());
		}
		// clone for image, need to copy over the image location.
		else if (given instanceof Image) {
			String url = ((Image) given).getUrl();
			widget = new Image(url);
		}
		// appending nulls is bad, this gives a visual queue that can't be
		// cloned.
		else {
			widget = new Label("?? set me up ??");
			throw new IllegalArgumentException(
					"Don't know how to clone the given item.");
		}

		// copy the style name
		widget.setStyleName(given.getStyleName());

		return widget;
	}
}
